<script type="text/javascript">
    $(document).ready(function(){
        $("#SignupForm").formToWizard({ submitButton: 'SaveAccount' })
        $('.next').click(function(){
            $('input#productname').val($('input#_productname').val()); 
            $('textarea#description').val($('textarea#description_').val());
            $('input#price').val($('input#_price').val());   
            $('input#end_time').val($('input#_end_time').val());
            $('input#category_id').val($('input#category_id_').val());
        }); 
        //$('.rlevel1').siblings().removeAttr('checked');
        //$('div.level0 ul').css({'list-style-type': 'none', 'height': '80px', 'width': '600px', 'margin': 'auto'});
        //$('div.level0 ul li').css('float: left');
    });
    $('#_end_time').ready(function(){
        $('#_end_time').datepicker({
            altFormat: "yy-mm-dd",
            changeYear: true,
            changeMonth: true,
            dateFormat: "yy-mm-dd",
            yearRange: "2011:2020"
        });
    });
    function getSubCat(id, level, nav){
        if(level == 1){
            $('.content').empty();
            //$('.level'+level+' ul').css({'list-style-type': 'none', 'height': '80px', 'width': '600px', 'margin': 'auto'});
        }
        $.ajax({
            type: "POST",
            url: "get_subcategory.php",
            data: "id="+id+"&level="+level+"&nav="+nav,
            success: function(data){        
                if(data == "" && level != 1){            
                    var a = parseInt(level) - 1;                    
                    while($('.level'+a).next().length != 0){
                        $('.level'+a).next().remove();                        
                    }
                }
                else{
                    if($('.level'+level).length==0){
                        $('.content').append(data);
                    }
                }
            }
        });
        
        $('.level'+level+' li').css('float: left');
    }
</script>
<script type="text/javascript">

//create a preview of the selection
function preview(img, selection) { 
	//get width and height of the uploaded image.
	var current_width = $('#uploaded_image').find('#thumbnail').width();
	var current_height = $('#uploaded_image').find('#thumbnail').height();

	var scaleX = <?php echo $thumb_width;?> / selection.width; 
	var scaleY = <?php echo $thumb_height;?> / selection.height; 
	
	$('#uploaded_image').find('#thumbnail_preview').css({ 
		width: Math.round(scaleX * current_width) + 'px', 
		height: Math.round(scaleY * current_height) + 'px',
		marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', 
		marginTop: '-' + Math.round(scaleY * selection.y1) + 'px' 
	});
	$('#x1').val(selection.x1);
	$('#y1').val(selection.y1);
	$('#x2').val(selection.x2);
	$('#y2').val(selection.y2);
	$('#w').val(selection.width);
	$('#h').val(selection.height);
} 

//show and hide the loading message
function loadingmessage(msg, show_hide){
	if(show_hide=="show"){
		$('#loader').show();
		$('#progress').show().text(msg);
		$('#uploaded_image').html('');
	}else if(show_hide=="hide"){
		$('#loader').hide();
		$('#progress').text('').hide();
	}else{
		$('#loader').hide();
		$('#progress').text('').hide();
		$('#uploaded_image').html('');
	}
}

//delete the image when the delete link is clicked.
function deleteimage(large_image, thumbnail_image){
	loadingmessage('Please wait, deleting images...', 'show');
	$.ajax({
		type: 'POST',
		url: '<?php echo $image_handling_file?>',
		data: 'a=delete&large_image='+large_image+'&thumbnail_image='+thumbnail_image,
		cache: false,
		success: function(response){
			loadingmessage('', 'hide');
			response = unescape(response);
			var response = response.split("|");
			var responseType = response[0];
			var responseMsg = response[1];
			if(responseType=="success"){
				$('#upload_status').show().html('<h1>Success</h1><p>'+responseMsg+'</p>');
				$('#uploaded_image').html('');
			}else{
				$('#upload_status').show().html('<h1>Unexpected Error</h1><p>Please try again</p>'+response);
			}
		}
	});
}

$(document).ready(function () {
		$('#loader').hide();
		$('#progress').hide();
		var myUpload = $('#upload_link').upload({
		   name: 'image',
		   action: '<?php echo $image_handling_file?>',
		   enctype: 'multipart/form-data',
		   params: {upload:'Upload'},
		   autoSubmit: true,
		   onSubmit: function() {
		   		$('#upload_status').html('').hide();
				loadingmessage('Please wait, uploading file...', 'show');
		   },
		   onComplete: function(response) {
		   		loadingmessage('', 'hide');
				response = unescape(response);
				var response = response.split("|");
				var responseType = response[0];
				var responseMsg = response[1];
				if(responseType=="success"){
					var current_width = response[2];
					var current_height = response[3];
					//display message that the file has been uploaded
					$('#upload_status').show().html('<h1>Success</h1><p>The image has been uploaded</p>');
					//put the image in the appropriate div
					$('#uploaded_image').html('<img src="'+responseMsg+'" style="float: left; margin-right: 10px;" id="thumbnail" alt="Create Thumbnail" /><div style="border:1px #e5e5e5 solid; float:left; position:relative; overflow:hidden; width:<?php echo $thumb_width;?>px; height:<?php echo $thumb_height;?>px;"><img src="'+responseMsg+'" style="position: relative;" id="thumbnail_preview" alt="Thumbnail Preview" /></div>')
					//find the image inserted above, and allow it to be cropped
					$('#uploaded_image').find('#thumbnail').imgAreaSelect({ aspectRatio: '1:<?php echo $thumb_height/$thumb_width;?>', onSelectChange: preview }); 
					//display the hidden form
					$('#thumbnail_form').show();
				}else if(responseType=="error"){
					$('#upload_status').show().html('<h1>Error</h1><p>'+responseMsg+'</p>');
					$('#uploaded_image').html('');
					$('#thumbnail_form').hide();
				}else{
					$('#upload_status').show().html('<h1>Unexpected Error</h1><p>Please try again</p>'+response);
					$('#uploaded_image').html('');
					$('#thumbnail_form').hide();
				}
		   }
		});
	
	//create the thumbnail
	$('#save_thumb').click(function() {
		var x1 = $('#x1').val();
		var y1 = $('#y1').val();
		var x2 = $('#x2').val();
		var y2 = $('#y2').val();
		var w = $('#w').val();
		var h = $('#h').val();
		if(x1=="" || y1=="" || x2=="" || y2=="" || w=="" || h==""){
			alert("You must make a selection first");
			return false;
		}else{
			//hide the selection and disable the imgareaselect plugin
			$('#uploaded_image').find('#thumbnail').imgAreaSelect({ disable: true, hide: true }); 
			loadingmessage('Please wait, saving thumbnail....', 'show');
			$.ajax({
				type: 'POST',
				url: '<?php echo $image_handling_file?>',
				data: 'save_thumb=Save Thumbnail&x1='+x1+'&y1='+y1+'&x2='+x2+'&y2='+y2+'&w='+w+'&h='+h,
				cache: false,
				success: function(response){
					loadingmessage('', 'hide');
					response = unescape(response);
					var response = response.split("|");
					var responseType = response[0];
					var responseLargeImage = response[1];
					var responseThumbImage = response[2];
					if(responseType=="success"){
						$('#upload_status').show().html('<h1>Success</h1><p>The thumbnail has been saved!</p>');
						//load the new images
						$('#uploaded_image').html('<img src="'+responseLargeImage+'" alt="Large Image"/>&nbsp;<img src="'+responseThumbImage+'" alt="Thumbnail Image"/><br /><a href="javascript:deleteimage(\''+responseLargeImage+'\', \''+responseThumbImage+'\');">Delete Images</a>');
						//hide the thumbnail form
						$('#thumbnail_form').hide();
					}else{
						$('#upload_status').show().html('<h1>Unexpected Error</h1><p>Please try again</p>'+response);
						//reactivate the imgareaselect plugin to allow another attempt.
						$('#uploaded_image').find('#thumbnail').imgAreaSelect({ aspectRatio: '1:<?php echo $thumb_height/$thumb_width;?>', onSelectChange: preview }); 
						$('#thumbnail_form').show();
					}
				}
			});
			
			return false;
		}
	});
}); 


//]]>
</script>
<?php
if(isset($_POST['btnSubmit']))
{   
    $product_name = addslashes($_POST['productname']);
    $category_id  = addslashes($_POST['category_id']);
    $description  = addslashes($_POST['description']);
    $price        = addslashes($_POST['price']);
    $end_time     = addslashes($_POST['end_time']);
    $fields_array = array('product_name' => "'$product_name'",
                          'category_id'  => "'$category_id'",
                          'description'  => "'$description'",
                          'price'        => "'$price'",
                          'start_time'   => "now()",
                          'end_time'     => "'$end_time'",
                          'create_date'  => "now()"         
                          );
    $result = insert("mid_products", $fields_array);
    if ($result)
        print "Sản phẩm {$product_name} đã được tạo. <a href='index.php'>Nhấp vào đây để xem</a>";
    else
        print "Có lỗi trong quá trình đăng bán, Vui lòng liên hệ BQT";      
}
else
{
?>
<form id="SignupForm" action="" method="post" enctype="multipart/form-data">
<style type="text/css">
        #main { width:900px; margin: 0px auto; border:solid 1px #b2b3b5; -moz-border-radius:10px; padding:20px; background-color:#f6f6f6;}
        fieldset { border:none; width:620px;}
        legend { font-size:18px; margin:0px; padding:10px 0px; color:#b0232a; font-weight:bold;}
        label { display:block; margin:15px 0 5px;}
        input[type=text], input[type=password] { width:300px; padding:5px; border:solid 1px #000;}
        .prev, .next { background-color:#b0232a; padding:5px 10px; color:#fff; text-decoration:none;}
        .prev:hover, .next:hover { background-color:#000; text-decoration:none;}
        .prev { float:left;}
        .next { float:right;}
        #steps { list-style:none; width:100%; overflow:hidden; margin:0px; padding:0px;}
        #steps li {font-size:24px; float:left; padding:10px; color:#b0b1b3;}
        #steps li span {font-size:11px; display:block;}
        #steps li.current1 { color:#000;}
        #makeWizard { background-color:#b0232a; color:#fff; padding:5px 10px; text-decoration:none; font-size:18px;}
        #makeWizard:hover { background-color:#000;}
        .level0 ul {list-style-type: none; height: 80px; width: 600px; margin: auto;}
        .level0 li {float: left;}
        .level1 ul {list-style-type: none; height: 80px; width: 600px; margin: auto;}
        .level1 li {float: left;}
        .level2 ul {list-style-type: none; height: 80px; width: 600px; margin: auto;}
        .level2 li {float: left;}
    </style>
<div id="main">
<fieldset>
    <legend>Đăng ký nhóm sản phẩm</legend>
    <label for="CategoryName">Chọn một trong những nhóm sản phẩm dưới đây để miêu tả sản phẩm bạn cần lên sàn 1 cách tốt nhất</label>
    <?php
    $arr = getCategory();
    echo '<div class="level0"><ul>';
    for($i=0; $i<count($arr['id']); $i++)
    {
    ?>
    <li>
        <input name="category_id_" class="rlevel0" id="<?php echo $arr['id'][$i]; ?>" type="radio" onclick="javascript:getSubCat(<?php echo $arr['id'][$i]; ?>,1,'<?php echo $arr['category_name'][$i]; ?>');" value="<?php echo $arr['id'][$i]; ?>" />
        <label for="<?php echo $arr['id'][$i]; ?>"><?php echo $arr['category_name'][$i]; ?></label>
    </li>
    <?php
    }
    echo '</ul></div>';
    ?>
    <div class="content"></div>
</fieldset>
<fieldset>
    <legend>Đăng ký lên sàn</legend>
    <label for="ProductName">Tên sản phẩm đăng bán</label>
    <input type="text" name="_productname" id="_productname" class="textInputreg" value=""/>
    <label for="Description">Mô tả</label>
    <textarea name="description_" id="description_" rows="5" cols="30"></textarea>
    <label for="Price">Giá đăng bán</label>
    <input type="text" name="_price" id="_price" class="textInputreg" value=""/>
    <label for="TimeEnd">Thời gian kết thúc</label>
    <input type="text" name="_end_time" id="_end_time" class="textInputreg" value=""/>
</fieldset>
<fieldset>
    <legend>Đăng hình sản phẩm lên sàn</legend>
    <label for="Image">Đăng hình sản phẩm</label>
    <h2>Upload Photo</h2>
	<div id="upload_status" style="font-size:12px; width:80%; margin:10px; padding:5px; display:none; border:1px #999 dotted; background:#eee;"></div>
	<p><a id="upload_link" style="background:#39f; font-size: 24px; color: white;" href="#">Click here to upload a photo</a></p>
	<span id="loader" style="display:none;"><img src="loader.gif" alt="Loading..."/></span> <span id="progress"></span>
	<br />
	<div id="uploaded_image"></div>
	<div id="thumbnail_form" style="display:none;">
		<form name="form" action="" method="post">
			<input type="hidden" name="x1" value="" id="x1" />
			<input type="hidden" name="y1" value="" id="y1" />
			<input type="hidden" name="x2" value="" id="x2" />
			<input type="hidden" name="y2" value="" id="y2" />
			<input type="hidden" name="w" value="" id="w" />
			<input type="hidden" name="h" value="" id="h" />
			<input type="submit" name="save_thumb" value="Save Thumbnail" id="save_thumb" />
		</form>
	</div>
    <!--<input type="file" name="uploadfile" value="" id="upload" /><span id="status" ></span><ul id="files"></ul>-->
</fieldset>
<fieldset>
    <legend>Đăng bán</legend>
    <label for="CategoryName">Chuyên mục</label>
    <input name="category_id" type="text" readonly="true" id="category_id" />
    <label for="ProductName">Tên sản phẩm đăng bán</label>
    <input type="text" name="productname" id="productname" readonly="true" class="textInputreg" value=""/>
    <label for="Description">Mô tả</label>
    <textarea name="description" id="description" readonly="true" rows="5" cols="30"></textarea>
    <label for="Price">Giá đăng bán</label>
    <input type="text" name="price" id="price" readonly="true" class="textInputreg" value=""/>
    <label for="TimeEnd">Thời gian kết thúc</label>
    <input type="text" name="end_time" id="end_time" readonly="true" class="textInputreg" value=""/>
</fieldset>
<p>
    <input id="SaveAccount" type="submit" name="btnSubmit" value="Đăng bán" />
</p>
</form>
</div>
<?php 
}
?>